package cheme.Application.actions;

import org.eclipse.core.runtime.Path;
import org.eclipse.jface.action.Action;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.actions.ActionFactory;

import cheme.Application.ChemeApplicationConstants;
import cheme.Application.ProjectSpaceModel.ChemeProjectModel;
import cheme.ProcessEditor.ChemeFileInput;
import cheme.ProcessEditor.ProcessEditor;

public class OpenFileAction extends Action implements ActionFactory.IWorkbenchAction
{
	String lastPath = "C:/";
	
	/**
     * The workbench window this action is registered with.
     */
    private IWorkbenchWindow workbenchWindow;
    
    public OpenFileAction(IWorkbenchWindow window)
    {
        //super(WorkbenchMessages.SaveAction_text, window); 
    	
    	super("Open File...");
        
    	if (window == null)
        {
            throw new IllegalArgumentException();
        }
    	
        workbenchWindow = window;
        
        setText("Open File...");
        setToolTipText("Open a chemical process file.");
        setId("open"); //$NON-NLS-1$
        
//        window.getWorkbench().getHelpSystem().setHelp(this, IWorkbenchHelpContextIds.SAVE_ACTION);
        
        setImageDescriptor(ChemeApplicationConstants.DESC_OPEN);
        setDisabledImageDescriptor(ChemeApplicationConstants.DESC_OPEN);
        
        setActionDefinitionId("org.eclipse.ui.file.save"); //$NON-NLS-1$
    }
    
    IWorkbenchWindow getWorkbenchWindow()
    {
    	return workbenchWindow;
    }
    
	@Override
	public void run()
	{
		FileDialog fd = new FileDialog(workbenchWindow.getShell(), SWT.OPEN);
		
		fd.setText("Open");
		fd.setFilterPath(lastPath);
        
		String[] filterExt = { "*.xml"};
		fd.setFilterExtensions(filterExt);
        
		String selected = fd.open();
		Path path = new Path(selected);
		String [] fileNames = fd.getFileNames();
		
		lastPath = path.uptoSegment(path.segmentCount() - 1).toString() + "/";
		
		for(String fileName : fileNames)
		{			
			ChemeFileInput input = ChemeProjectModel.getInstance().getFile(lastPath + fileName);
			
			try
			{
				getWorkbenchWindow().getActivePage().openEditor((IEditorInput)input, ProcessEditor.ID);
			}
			catch(Exception e)
			{
				e.printStackTrace();
			}
		}

//		super.run();
	}

	public void dispose()
	{
		// TODO Auto-generated method stub
		
	}
}
